Expand description
Wasmtime’s embedding API
Wasmtime is a WebAssembly engine for JIT-compiled or ahead-of-time compiled
WebAssembly modules. More information about the Wasmtime project as a whole
can be found in the documentation book whereas
this documentation mostly focuses on the API reference of the wasmtime
crate itself.
This crate contains an API used to interact with WebAssembly modules. For example you can compile modules, instantiate them, call them, etc. As an embedder of WebAssembly you can also provide WebAssembly modules functionality from the host by creating host-defined functions, memories, globals, etc, which can do things that WebAssembly cannot (such as print to the screen).
The wasmtime
crate has similar concepts to the
the JS WebAssembly
API as well as the
proposed C API, but the Rust
API is designed for efficiency, ergonomics, and expressivity in Rust. As
with all other Rust code you’re guaranteed that programs will be safe (not
have undefined behavior or segfault) so long as you don’t use unsafe
in
your own program. With wasmtime
you can easily and conveniently embed a
WebAssembly runtime with confidence that the WebAssembly is safely
sandboxed.
An example of using Wasmtime looks like:
use wasmtime::*;
fn main() -> wasmtime::Result<()> {
// Modules can be compiled through either the text or binary format
let engine = Engine::default();
let wat = r#"
(module
(import "host" "host_func" (func $host_hello (param i32)))
(func (export "hello")
i32.const 3
call $host_hello)
)
"#;
let module = Module::new(&engine, wat)?;
// All wasm objects operate within the context of a "store". Each
// `Store` has a type parameter to store host-specific data, which in
// this case we're using `4` for.
let mut store = Store::new(&engine, 4);
let host_func = Func::wrap(&mut store, |caller: Caller<'_, u32>, param: i32| {
println!("Got {} from WebAssembly", param);
println!("my host state is: {}", caller.data());
});
// Instantiation of a module requires specifying its imports and then
// afterwards we can fetch exports by name, as well as asserting the
// type signature of the function with `get_typed_func`.
let instance = Instance::new(&mut store, &module, &[host_func.into()])?;
let hello = instance.get_typed_func::<(), ()>(&mut store, "hello")?;
// And finally we can call the wasm!
hello.call(&mut store, ())?;
Ok(())
}
§Core Concepts
There are a number of core types and concepts that are important to be aware
of when using the wasmtime
crate:
-
Engine
- a global compilation environment for WebAssembly. AnEngine
is an object that can be shared concurrently across threads and is created with aConfig
to tweak various settings. Compilation of any WebAssembly requires first configuring and creating anEngine
. -
Module
- a compiled WebAssembly module. This structure represents in-memory JIT code which is ready to execute after being instantiated. It’s often important to cache instances of aModule
because creation (compilation) can be expensive. Note thatModule
is safe to share across threads, and can be created from a WebAssembly binary and anEngine
withModule::new
. Caching can either happen withEngine::precompile_module
orModule::serialize
, feeding those bytes back intoModule::deserialize
. -
Store
- container for all information related to WebAssembly objects such as functions, instances, memories, etc. AStore<T>
allows customization of theT
to store arbitrary host data within aStore
. This host data can be accessed through host functions via theCaller
function parameter in host-defined functions. AStore
is required for all WebAssembly operations, such as calling a wasm function. TheStore
is passed in as a “context” to methods likeFunc::call
. Dropping aStore
will deallocate all memory associated with WebAssembly objects within theStore
. -
Instance
- an instantiated WebAssembly module. An instance is where you can actually acquire aFunc
from, for example, to call. -
Func
- a WebAssembly (or host) function. This can be acquired as the export of anInstance
to call WebAssembly functions, or it can be created via functions likeFunc::wrap
to wrap host-defined functionality and give it to WebAssembly. -
Table
,Global
,Memory
- other WebAssembly objects which can either be defined on the host or in wasm itself (via instances). These all have various ways of being interacted with likeFunc
.
All “store-connected” types such as Func
, Memory
, etc, require the
store to be passed in as a context to each method. Methods in wasmtime
frequently have their first parameter as either impl AsContext
or impl AsContextMut
. These
traits are implemented for a variety of types, allowing you to, for example,
pass the following types into methods:
&Store<T>
&mut Store<T>
&Caller<'_, T>
&mut Caller<'_, T>
StoreContext<'_, T>
StoreContextMut<'_, T>
A Store
is the sole owner of all WebAssembly internals. Types like
Func
point within the Store
and require the Store
to be provided
to actually access the internals of the WebAssembly function, for instance.
§Linking
WebAssembly modules almost always require functionality from the host to
perform I/O-like tasks. They might refer to quite a few pieces of host
functionality, WASI, or maybe even a number of other wasm modules. To assist
with managing this a Linker
type is provided to instantiate modules.
A Linker
performs name-based resolution of the imports of a WebAssembly
module so the Linker::instantiate
method does not take an imports
argument like Instance::new
does. Methods like Linker::define
or
Linker::func_wrap
can be used to define names within a Linker
to
later be used for instantiation.
For example we can reimplement the above example with a Linker
:
use wasmtime::*;
fn main() -> wasmtime::Result<()> {
let engine = Engine::default();
let wat = r#"
(module
(import "host" "host_func" (func $host_hello (param i32)))
(func (export "hello")
i32.const 3
call $host_hello)
)
"#;
let module = Module::new(&engine, wat)?;
// Create a `Linker` and define our host function in it:
let mut linker = Linker::new(&engine);
linker.func_wrap("host", "host_func", |caller: Caller<'_, u32>, param: i32| {
println!("Got {} from WebAssembly", param);
println!("my host state is: {}", caller.data());
})?;
// Use the `linker` to instantiate the module, which will automatically
// resolve the imports of the module using name-based resolution.
let mut store = Store::new(&engine, 0);
let instance = linker.instantiate(&mut store, &module)?;
let hello = instance.get_typed_func::<(), ()>(&mut store, "hello")?;
hello.call(&mut store, ())?;
Ok(())
}
The Linker
type also transparently handles Commands and Reactors
as defined by WASI.
§Example Architecture
To better understand how Wasmtime types interact with each other let’s walk
through, at a high-level, an example of how you might use WebAssembly. In
our use case let’s say we have a web server where we’d like to run some
custom WebAssembly on each request. To ensure requests are entirely isolated
from each other, though, we’ll be creating a new Store
for each
request.
When the server starts, we’ll start off by creating an Engine
(and maybe
tweaking Config
settings if necessary). This Engine
will be the only
engine for the lifetime of the server itself. Next, we can compile our
WebAssembly. You’d create a Module
through the Module::new
API.
This will generate JIT code and perform expensive compilation tasks
up-front. Finally the last step of initialization would be to create a
Linker
which will later be used to instantiate modules, adding
functionality like WASI to the linker too.
After that setup, the server starts up as usual and is ready to receive
requests. Upon receiving a request you’d then create a Store
with
Store::new
referring to the original Engine
. Using your Module
and Linker
from before you’d then call Linker::instantiate
to
instantiate our module for the request. Both of these operations are
designed to be as cheap as possible.
With an Instance
you can then invoke various exports and interact with
the WebAssembly module. Once the request is finished, the Store
is dropped and everything will be deallocated. Note that if the same
Store
were used for every request then that would have all requests
sharing resources and nothing would ever get deallocated, causing memory
usage to baloon and would achive less isolation between requests.
§WASI
The wasmtime
crate does not natively provide support for WASI, but you can
use the wasmtime-wasi
crate for that purpose. With wasmtime-wasi
all
WASI functions can be added to a Linker
and then used to instantiate
WASI-using modules. For more information see the WASI example in the
documentation.
§Cross-store usage of items
In wasmtime
wasm items such as Global
and Memory
“belong” to a
Store
. The store they belong to is the one they were created with
(passed in as a parameter) or instantiated with. This store is the only
store that can be used to interact with wasm items after they’re created.
The wasmtime
crate will panic if the Store
argument passed in to these
operations is incorrect. In other words it’s considered a programmer error
rather than a recoverable error for the wrong Store
to be used when
calling APIs.
§Crate Features
The wasmtime
crate comes with a number of compile-time features that can
be used to customize what features it supports. Some of these features are
just internal details, but some affect the public API of the wasmtime
crate. Be sure to check the API you’re using to see if any crate features
are enabled.
-
runtime
- Enabled by default, this feature enables executing WebAssembly modules. If modules are only compiled, however, this feature can be disabled. -
cranelift
- Enabled by default, this features enables using Cranelift at runtime to compile a WebAssembly module to native code. This feature is required to process and compile new WebAssembly modules. If this feature is disabled then the only way to create aModule
is to use theModule::deserialize
function with a precompiled artifact (typically compiled with the same version of Wasmtime, just somewhere else). -
cache
- Enabled by default, this feature adds support for wasmtime to perform internal caching of modules in a global location. This must still be enabled explicitly throughConfig::cache_config_load
orConfig::cache_config_load_default
. -
wat
- Enabled by default, this feature adds support for accepting the text format of WebAssembly inModule::new
. The text format will be automatically recognized and translated to binary when compiling a module. -
parallel-compilation
- Enabled by default, this feature enables support for compiling functions of a module in parallel withrayon
. -
async
- Enabled by default, this feature enables APIs and runtime support for defining asynchronous host functions and calling WebAssembly asynchronously. -
jitdump
- Enabled by default, this feature compiles in support for the jitdump runtime profiling format. The profiler can be selected withConfig::profiler
. -
vtune
- Enabled by default, this feature compiles in support for VTune profiling of JIT code. -
all-arch
- Not enabled by default. This feature compiles in support for all architectures for both the JIT compiler and thewasmtime compile
CLI command. -
pooling-allocator
- Enabled by default, this feature adds support for the pooling allocation strategy enabled viaConfig::allocation_strategy
. The pooling allocator can enable more efficient reuse of resources for high-concurrency and high-instantiation-count scenarios. -
memory-init-cow
- Enabled by default, this feature builds in support for, on supported platforms, initializing wasm linear memories with copy-on-write heap mappings. This makes instantiation much faster bymmap
-ing the initial memory image into place instead of copying memory into place, allowing sharing pages that end up only getting read. Note that this is simply compile-time support and this must also be enabled at run-time viaConfig::memory_init_cow
(which is also enabled by default). -
demangle
- Enabled by default, this will affect how backtraces are printed and whether symbol names from WebAssembly are attempted to be demangled. Rust and C++ demanglings are currently supported. -
coredump
- Enabled by default, this will provide support for generating a core dump when a trap happens. This can be configured viaConfig::coredump_on_trap
. -
addr2line
- Enabled by default, this feature configures whether traps will attempt to parse DWARF debug information and convert WebAssembly addresses to source filenames and line numbers. -
debug-builtins
- Enabled by default, this feature includes some built-in debugging utilities and symbols for native debuggers such as GDB and LLDB to attach to the process Wasmtime is used within. The intrinsics provided will enable debugging guest code compiled to WebAssembly. This must also be enabled viaConfig::debug_info
as well for guests.
More crate features can be found in the manifest of Wasmtime itself for seeing what can be enabled and disabled.
§Examples
In addition to the examples below be sure to check out the online embedding documentation as well as the online list of examples
An example of using WASI looks like:
use wasi_common::sync::WasiCtxBuilder;
// Compile our module and create a `Linker` which has WASI functions defined
// within it.
let engine = Engine::default();
let module = Module::from_file(&engine, "foo.wasm")?;
let mut linker = Linker::new(&engine);
wasi_common::sync::add_to_linker(&mut linker, |cx| cx)?;
// Configure and create a `WasiCtx`, which WASI functions need access to
// through the host state of the store (which in this case is the host state
// of the store)
let wasi_ctx = WasiCtxBuilder::new().inherit_stdio().build();
let mut store = Store::new(&engine, wasi_ctx);
// Instantiate our module with the imports we've created, and run it.
let instance = linker.instantiate(&mut store, &module)?;
// ...
An example of reading a string from a wasm module:
use std::str;
let mut store = Store::default();
let log_str = Func::wrap(&mut store, |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
// Use our `caller` context to learn about the memory export of the
// module which called this host function.
let mem = match caller.get_export("memory") {
Some(Extern::Memory(mem)) => mem,
_ => anyhow::bail!("failed to find host memory"),
};
// Use the `ptr` and `len` values to get a subslice of the wasm-memory
// which we'll attempt to interpret as utf-8.
let data = mem.data(&caller)
.get(ptr as u32 as usize..)
.and_then(|arr| arr.get(..len as u32 as usize));
let string = match data {
Some(data) => match str::from_utf8(data) {
Ok(s) => s,
Err(_) => anyhow::bail!("invalid utf-8"),
},
None => anyhow::bail!("pointer/length out of bounds"),
};
assert_eq!(string, "Hello, world!");
println!("{}", string);
Ok(())
});
let module = Module::new(
store.engine(),
r#"
(module
(import "" "" (func $log_str (param i32 i32)))
(func (export "foo")
i32.const 4 ;; ptr
i32.const 13 ;; len
call $log_str)
(memory (export "memory") 1)
(data (i32.const 4) "Hello, world!"))
"#,
)?;
let instance = Instance::new(&mut store, &module, &[log_str.into()])?;
let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
foo.call(&mut store, ())?;
Modules§
- component
runtime
andcomponent-model
In-progress implementation of the WebAssembly component model - Memory Protection Keys (MPK) implementation for use in striped memory allocation.
- unix
runtime
Unix-specific extension for thewasmtime
crate.
Structs§
- Caller
runtime
A structure representing the caller’s context when creating a function viaFunc::wrap
. - CodeMemory
runtime
Management of executable memory within aMmapVec
- CompiledModule
runtime
A compiled wasm module, ready to be instantiated. - Global configuration options used to create an
Engine
and customize its behavior. - An
Engine
which is a global context for compilation and management of wasm modules. - A weak reference to an
Engine
. - A convenience wrapper for
Result<T, anyhow::Error>
. - Export
runtime
An exported WebAssembly value. - ExportType
runtime
A descriptor for an exported WebAssembly value. - ExternRef
runtime
Represents an opaque reference to any data within WebAssembly. - FrameInfo
runtime
Description of a frame in a backtrace for aWasmBacktrace
. - FrameSymbol
runtime
Debug information for a symbol that is attached to aFrameInfo
. - Func
runtime
A WebAssembly function which can be called. - FuncType
runtime
A descriptor for a function in a WebAssembly module. - Global
runtime
A WebAssemblyglobal
value which can be read and written to. - GlobalType
runtime
A WebAssembly global descriptor. - GuestProfiler
runtime
Collects basic profiling data for a single WebAssembly guest. - ImportType
runtime
A descriptor for an imported value into a wasm module. - Instance
runtime
An instantiated WebAssembly module. - InstancePre
runtime
An instance, pre-instantiation, that is ready to be instantiated. - Linker
runtime
Structure used to link wasm modules/instances together. - Memory
runtime
A WebAssembly linear memory. - MemoryAccessError
runtime
Error for out of boundsMemory
access. - MemoryType
runtime
A descriptor for a WebAssembly memory type. - Module
runtime
A compiled WebAssembly module, ready to be instantiated. - ModuleExport
runtime
Describes the location of an export in a module. - Configuration options used with
InstanceAllocationStrategy::Pooling
to change the behavior of the pooling instance allocator. - ResourcesRequired
runtime
- SharedMemory
runtime
A constructor for externally-created shared memory. - Store
runtime
AStore
is a collection of WebAssembly instances and host-defined state. - StoreContext
runtime
A temporary handle to a&Store<T>
. - StoreContextMut
runtime
A temporary handle to a&mut Store<T>
. - StoreLimits
runtime
Provides limits for aStore
. - StoreLimitsBuilder
runtime
Used to buildStoreLimits
. - Table
runtime
A WebAssemblytable
, or an array of values. - TableType
runtime
A descriptor for a table in a WebAssembly module. - TypedFunc
runtime
A statically typed WebAssembly function. - UnknownImportError
runtime
Error for an unresolvable import. - V128
runtime
Representation of a 128-bit vector type,v128
, for WebAssembly. - WasmBacktrace
runtime
Representation of a backtrace of function frames in a WebAssembly module for where an error happened. - WasmCoreDump
runtime
Representation of a core dump of a WebAssembly module
Enums§
- CallHook
runtime
Passed to the argument ofStore::call_hook
to indicate a state transition in the WebAssembly VM. - Extern
runtime
An external item to a WebAssembly module, or a list of what can possibly be exported from a wasm module. - ExternType
runtime
A list of all possible types which can be externally referenced from a WebAssembly module. - Represents the module instance allocation strategy to use.
- Configure the strategy used for versioning in serializing and deserializing
crate::Module
. - Describe the tri-state configuration of memory protection keys (MPK).
- Mutability
runtime
Indicator of whether a global is mutable or not - Possible optimization levels for the Cranelift codegen backend.
- Return value from the
Engine::detect_precompiled
API. - Select which profiling technique to support.
- Possible Compilation strategies for a wasm module.
- Representation of a WebAssembly trap and what caused it to occur.
- UpdateDeadline
runtime
What to do after returning from a callback when the engine epoch reaches the deadline for a Store during execution of a function using that store. - Val
runtime
Possible runtime values that a WebAssembly module can either consume or produce. - ValType
runtime
A list of all possible value types in WebAssembly. - Result of
Memory::atomic_wait32
andMemory::atomic_wait64
- Select how wasm backtrace detailed information is handled.
Constants§
- DEFAULT_INSTANCE_LIMIT
runtime
Value returned byResourceLimiter::instances
default method - DEFAULT_MEMORY_LIMIT
runtime
Value returned byResourceLimiter::memories
default method - DEFAULT_TABLE_LIMIT
runtime
Value returned byResourceLimiter::tables
default method
Traits§
- AsContext
runtime
A trait used to get shared access to aStore
in Wasmtime. - AsContextMut
runtime
A trait used to get exclusive mutable access to aStore
in Wasmtime. - Implementation of an incremental compilation’s key/value cache store.
- CallHookHandler
runtime
An object that can take callbacks when the runtime enters or exits hostcalls. - IntoFunc
runtime
Internal trait implemented for all arguments that can be passed toFunc::wrap
andLinker::func_wrap
. - LinearMemory
runtime
A linear memory. This trait provides an interface for raw memory buffers which are used by wasmtime, e.g. inside [‘Memory’]. Such buffers are in principle not thread safe. By implementing this trait together with MemoryCreator, one can supply wasmtime with custom allocated host managed memory. - MemoryCreator
runtime
A memory creator. Can be used to provide a memory creator to wasmtime which supplies host managed memory. - ResourceLimiter
runtime
Used by hosts to limit resource consumption of instances. - ResourceLimiterAsync
runtime
Used by hosts to limit resource consumption of instances, blocking asynchronously if necessary. - StackCreator
runtime
A stack creator. Can be used to provide a stack creator to wasmtime which supplies stacks for async support. - StackMemory
runtime
A stack memory. This trait provides an interface for raw memory buffers which are used by wasmtime inside of stacks which wasmtime executes WebAssembly in for async support. By implementing this trait together with StackCreator, one can supply wasmtime with custom allocated host managed stacks. - WasmParams
runtime
A trait used forFunc::typed
and withTypedFunc
to represent the set of parameters for wasm functions. - WasmResults
runtime
A trait used forFunc::typed
and withTypedFunc
to represent the set of results for wasm functions. - WasmRet
runtime
A trait implemented for types which can be returned from closures passed toFunc::wrap
and friends. - WasmTy
runtime
A trait implemented for types which can be arguments and results for closures passed toFunc::wrap
as well as parameters toFunc::typed
.
Type Aliases§
- A convenience wrapper for
Result<T, anyhow::Error>
.
Unions§
- A “raw” and unsafe representation of a WebAssembly value.